package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.damain.Dish;
import com.itheima.reggie.service.DishControllerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DishController {
    @Autowired
    private DishControllerService dishControllerService;
    @Autowired
    private RedisTemplate redisTemplate;

    //修改：使用注释优化程序，提高数据库的利用率，
//    具体：将查询过的数据保存到redis中，如果重复查询时，会从redis中获取数据
//    对于部分操作，如增删改 redis会重新从数据库中读取数据
    //根据菜品id查内容
    @GetMapping("/dish/list")
    public ResultInfo findbyid(Long categoryId, Integer status) {
        //操作字符串结构的对象
        String key = "dish-" + categoryId;
        ValueOperations ops=redisTemplate.opsForValue();

        //想从redis中查询，没有查到则到数据库中查询
        List<Dish>dishList= (List<Dish>) ops.get(key);
        if (CollectionUtils.isNotEmpty(dishList)){
            //从redis中获取数据
            return ResultInfo.success(dishList);
        }else {
            //从数据库中获取数据
            dishList=dishControllerService.findlist(categoryId,null);
            //保存到前端
            ops.set(key,dishList);
            return ResultInfo.success(dishList);
        }
//        List<Dish> dishList = dishControllerService.findlist(categoryId, null);
//        return ResultInfo.success(dishList);

    }
}
